package 行为型模式.迭代器模式;

import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * 主要组成部分
 * 迭代器接口 (Iterator Interface):
 * 定义访问和遍历元素的接口
 * 通常包含 next(), hasNext(), currentItem() 等方法
 * 具体迭代器 (Concrete Iterator):
 * 实现迭代器接口
 * 跟踪遍历的当前位置
 * 聚合接口 (Aggregate Interface):
 * 定义创建相应迭代器对象的接口
 * 通常是一个 createIterator() 方法
 * 具体聚合 (Concrete Aggregate):
 * 实现聚合接口
 * 返回具体迭代器的实例
 */

//定义书类
class Book
{
	private String name;
	
	Book(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
}

//定义迭代器
interface Iterators<T> {
	boolean hasNext();
	T next();
}

// 3. 定义书架聚合接口
interface IBookShelf 
{
	Iterators<Book> iterators();
}

class Bookshelf implements IBookShelf
{
	private Book[] books;//书籍
	private int last = 0;//位置

	Bookshelf(int max) {
		this.books = new Book[max];
	}
	
	public Book getBookAt(int index) {
		return books[index];
	}

	public void appendBook(Book book) {
		this.books[last] = book;
		last++;
	}

	public int getLength() {
		return last;
	}

	@Override
	public Iterators<Book> iterators() {
		return new BookShelfIterator(this);
	}
}

//迭代器
class BookShelfIterator implements Iterators<Book>
{
	private Bookshelf bookShelf;
	private int index;

	public BookShelfIterator(Bookshelf bookShelf) {
		this.bookShelf = bookShelf;
		this.index = 0;
	}
	
	@Override
	public boolean hasNext() {
		return index < bookShelf.getLength();
	}

	@Override
	public Book next() {
		Book book = bookShelf.getBookAt(index);
		index++;
		return book;
	}
}

public class Iterator 
{
	public static void main(String[] args) 
	{
		Bookshelf bookshelf = new Bookshelf(5);
		bookshelf.appendBook(new Book("JAVA"));
		bookshelf.appendBook(new Book("C#"));
		bookshelf.appendBook(new Book("C++"));

		Iterators<Book> iterators = bookshelf.iterators();
		
		while (iterators.hasNext())
		{
			System.out.println(iterators.next().getName());
		}
	}
}
